﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Utilities.Common
{ 
    public class ClassInfo
    {
        //public object Item { get; set; }//no usar porque me ata a una instancia del objeto
        public string ClassName { get; set; }
        public ITableName TableName { get; set; }
        public string FieldPrefix { get; set; }
        public PropInfoManager Properties { get; set; }

        internal IProxy Proxy { get; set; }

        public static ClassInfo BuildClassInfo(object obj)
        {
            ClassInfo clase = new ClassInfo();           
            clase.TableName = GetTableName(obj);
            clase.ClassName = obj.GetType().Name;
            clase.FieldPrefix = GetTablePrefix(obj);
            clase.Properties = GetParameters(clase, obj);

            clase.Proxy = ProxyBuilder.Build(clase, obj);

            clase.Properties.PropId = clase.Properties.Find(p => p.IsId);

            return clase;
        }

        public object GetNew()
        {
            return Proxy.GetNew();
        }

        private static string GetTablePrefix(object obj)
        {
            string prefix = "";
            Attribute attribute = AttributeHelper.GetAttribute(obj, typeof(FieldPrefixAttribute));
            if (attribute != null)
            {
                prefix = ((FieldPrefixAttribute)attribute).Prefix;
            }
            return prefix;
        }

        private static ITableName GetTableName(object obj)
        {
            ITableName table;
            Attribute attribute = AttributeHelper.GetAttribute(obj, typeof(TableNameAttribute));
            if (attribute != null)
            {
                table = new TN(((TableNameAttribute)attribute).TableName);
            }
            else
            {
                table = new TN(obj.GetType().Name);//sino tomo el nombre de la clase
            }
            return table;
        }

        private static PropInfoManager GetParameters(ClassInfo classInfo, object obj)
        {
            Type info = obj.GetType();
            System.Reflection.PropertyInfo[] properties = info.GetProperties();

            PropInfoManager parameters = new PropInfoManager();
            PropInfo parameter;
            foreach (System.Reflection.PropertyInfo p in properties)
            {
                parameter = PropInfo.GetPropertyInfo(classInfo, obj, p);
                if (parameter != null)
                {
                    parameters.Add(parameter);
                }
            }
            return parameters;
        }

    }
    internal class TN : ITableName
    {
        public TN(string name)
        {
            Name = name;
        }

        public string  Name { get; set; }
    }
}
